from studenthoods.apps.facebook.models import Entrant, FacebookCompetition, University, SIZE_CHOICES
from studenthoods.apps.common import widgets
from django.forms import Select, HiddenInput
from django import forms
from datetime import date


class EntryForm(forms.Form):

    name = forms.CharField(max_length=200,required=True, label='Full name')
    email = forms.EmailField(max_length=200, required=True, label='Email')
    email_confirm = forms.EmailField(max_length=200, required=True, label='Confirm your email')
    size = forms.ChoiceField(widget=Select, choices=SIZE_CHOICES, label='Select a size')
    t_and_cs = forms.BooleanField(required=True, label='I agree to the <a href="{% url terms_and_conditions %}" target="_blank" title="(opens in new window)">Terms and Conditions</a>')

    def __init__(self, *args, **kw):

        super(EntryForm, self).__init__(*args, **kw)

        extra_errors = {
            'name':{'required':'Please enter your Name'},
            'email':{'required':'Please enter your Email address'},
            'email_confirm':{'required':'Please confirm your Email address'},
            'size':{'required':'Please select a Size'},
            't_and_cs':{'required':'Please agree to the Terms and Conditions'},
        }

        for field, errors in extra_errors.iteritems():
            self.fields[field].error_messages.update(errors)

    def clean(self):
        super(EntryForm, self).clean()

        self.clean_size()
        self.clean_email()
        self.clean_email_confirm()
        return self.cleaned_data

    def clean_email(self):
        if 'email' in self.cleaned_data:
            email = self.cleaned_data['email']

            try:
                Entrant.objects.get(email=email)
                raise forms.ValidationError('This Email Address is already entered')
            except Entrant.DoesNotExist:
                return self.cleaned_data['email']

    def clean_email_confirm(self):
        if ('email' in self.cleaned_data) and \
            ('email_confirm' in self.cleaned_data):

            email = str(self.cleaned_data['email'])
            email_confirm = str(self.cleaned_data['email_confirm'])

            if email != email_confirm:
                raise forms.ValidationError('Your Confirmation Email does not match your original Email.')
            else:
                return self.cleaned_data['email_confirm']

    def clean_size(self):
        if ('size' in self.cleaned_data):

            size = str(self.cleaned_data['size'])

            if size == '':
                raise forms.ValidationError('Please select a size.')
            elif not size:
                raise forms.ValidationError('Please select a valid size.')
            else:
                return self.cleaned_data['size']